package com.calabar.flume.tcp.client;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class TCPClientHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private ChannelHandlerContext ctx;


    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        for (int i = 0; i < 1000; i++) {
            byte[] data = proData();
            long start = System.currentTimeMillis();
            ByteBuf encoded = ctx.alloc().buffer(data.length);
            encoded.writeBytes(data);
            ctx.writeAndFlush(encoded);
            long end = System.currentTimeMillis();
            System.out.println("第"+i+"次，发送耗时："+(end-start));
//            Thread.sleep(1000);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("捕获异常");
    }

    @Override
    protected void messageReceived(ChannelHandlerContext channelHandlerContext, ByteBuf byteBuf) throws Exception {
        System.out.println("message Received");
    }

    public static byte[] proData() throws InterruptedException {
        byte[] bytes = new byte[8000];
        List<Byte> data = new ArrayList<Byte>();
        List<Float> data1 = new ArrayList<Float>();
        Random random = new Random();
        long start = System.currentTimeMillis();
        for (int i = 0; i < 2000; i++) {
            Float f = random.nextFloat();
            data1.add(f);
            byte[] b = ByteBuffer.allocate(4).putFloat(f).array();
            for (int j = b.length-1; j >=0; j--) {
                data.add(b[j]);
            }
        }
        long end = System.currentTimeMillis();
        for (int i = 0; i < data.size(); i++) {
            bytes[i]=data.get(i);
        }

        System.out.println("数据准备时间：" + (end - start));
//        for (int i = 0; i < data1.size(); i++) {
//            System.out.println(data1.get(i));
//        }
        return bytes;
    }
}